import dynamic from 'next/dynamic'
import ProjectItem from '@c/sports/project-item'
import HotItem from '@c/sports/hot-item'
import FocusMatchItem from '@c/sports/focus-match-item'
import HotRaceItem from '@c/sports/hot-race-item'
import Footer from '@c/footer'
import Responsive from '@c/responsive'
import styles from './index.module.scss'
import { getProject, getHotRace, getHeader, getFocusMatch } from '@/api/sports'
import { useEffect, useState } from 'react'
import cm from 'classnames'
import Link from 'next/link'
import { formatDate } from '@/utils/date'
import { SPORT_INFO, HOT_RACE_ARR } from '@/constant'
import { useRouter } from 'next/router'

const GuideDownload = dynamic(() => import('@c/guide-download'))

const urlObj = SPORT_INFO.reduce((final, target) => {
  final[target.name] = target.url
  return final
}, {})

const isTodayFunc = target => {
  const today = new Date()
  const targetDate = new Date(target)
  return (
    today.getFullYear() === targetDate.getFullYear() && today.getMonth() === targetDate.getMonth() &&
    today.getDate() === targetDate.getDate()
  )
}
export default function Sports(props) {
  const router = useRouter()
  const { headerInfo, project = [], hotRace } = props
  const isToday = isTodayFunc(headerInfo.startTime)
  const [focusRace, setFocusRace] = useState([])
  const [currTab, setTab] = useState(1)
  const [commData, setCommData] = useState(hotRace)
  const dateObj = formatDate(headerInfo?.startTime || new Date())
  //获取焦点赛
  const fetchFocusMatch = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
      return
    }
    const res = await getFocusMatch(token)
    setFocusRace(res?.data?.matchItemList || [])
  }

  const toLivePlay = () => {
    router.push(`/sports/live/${headerInfo?.matchID}`)
  }
  useEffect(() => {
    fetchFocusMatch()
    return () => {
      sessionStorage.setItem('lastPage', true)
    }
  }, [])

  useEffect(() => {
    setCommData(currTab == 1 ? hotRace : focusRace)
  }, [currTab])
  return (
    <>
      <div className={styles.sportHome}>
        <div className={cm(styles.sportBg, styles.bannerPhone)} onClick={toLivePlay}>
          <p className={styles.cp}>{headerInfo.competition}</p>
          {!headerInfo.confrontTeams?.length ? (
            <>
              <p className={styles.cpTitle}>{headerInfo.title}</p>
            </>
          ) : (
            <div className={styles.teamBanner}>
              <div className={styles.img} data-name={headerInfo.confrontTeams[0]?.name}>
                <img loading="lazy" src={headerInfo.confrontTeams[0]?.image} alt={headerInfo.confrontTeams[0]?.name} />
              </div>
              <span className={styles.vs}>VS</span>
              <div className={styles.img} data-name={headerInfo.confrontTeams[1]?.name}>
                <img loading="lazy" src={headerInfo.confrontTeams[1]?.image} alt={headerInfo.confrontTeams[1]?.name} />
              </div>
            </div>
          )}
          <p className={styles.cpDate}>
            {isToday ? '今天' : `${dateObj.month}月${dateObj.day}日`} {`${dateObj.hour}:${dateObj.minutes}`}
          </p>
          <img loading="lazy" src={headerInfo?.tvBanner} alt="电视" className={styles.img} />
          <Responsive className={cm(styles.projectBox, 'hideWhenPhone')}>
            <ProjectItem data={project} />
          </Responsive>
        </div>
        <div className={cm(styles.projectPhone, 'hideWhenPc', 'scrollBeautify')}>
          {project.map((item, index) => {
            return (
              <Link href={'/sports/' + urlObj[item.name]} key={index} className={styles.items}>
                <img loading="lazy" src={item.icon} className={styles.img} alt={item.name} />
                <span>{item.name}</span>
              </Link>
            )
          })}
        </div>
        <Responsive className={'hideWhenPhone'}>
          <h2 className={styles.hotTitle}>热门赛程</h2>
          <HotItem data={hotRace} />
          <GuideDownload top={40} bottom={56} />
          <h2 className={styles.hotRaceTitle}>热门赛事</h2>
          <HotRaceItem />
          {focusRace?.length ? (
            <>
              <h2 className={styles.myRace} style={{ marginTop: 30 }}>
                我的焦点赛
              </h2>
              <FocusMatchItem data={focusRace} />
            </>
          ) : null}
          <Footer />
        </Responsive>

        {/* 以下是移动端代码 */}
        <GuideDownload top={12} className="hideWhenPc" />
        <div className={cm(styles.commHotRace, 'hideWhenPc')}>
          <p className={styles.hTitle}>热门赛事</p>
          <div className={styles.hotBox}>
            {HOT_RACE_ARR.map((item, index) => {
              return (
                <Link href={`/sports/${item.url}`} key={index} className={styles.item}>
                  <img loading="lazy" src={item.icon} alt={item.name} />
                  <span>{item.name}</span>
                </Link>
              )
            })}
          </div>
        </div>
        <div className={cm(styles.switchTab, 'hideWhenPc')}>
          <div className={cm(styles.item, currTab == 1 ? styles.itemActive : '')} onClick={() => setTab(1)}>
            热门赛事
          </div>
          <div className={cm(styles.item, currTab == 2 ? styles.itemActive : '')} onClick={() => setTab(2)}>
            我的焦点赛
          </div>
        </div>
        <div className={'hideWhenPc'}>
          {commData?.map((item, index) => {
            const group = item?.confrontTeams || []
            return (
              <Link href={`/sports/live/${item.matchID}`} className={styles.commData} key={index}>
                <p className={styles.date}>
                  <span>{item.keyWord.slice(0, 6)}</span>
                  <span style={{ marginLeft: 6 }}>{item.keyWord.slice(-4)}</span>
                </p>
                <p className={styles.title}>{item.title}</p>
                <div className={styles.teams}>
                  {group.length < 2 ? null : (
                    <>
                      <span className={styles.name}>{group[0].name}</span>
                      <img
                        loading="lazy"
                        src={group[0].image}
                        alt={group[0].name}
                        className={cm(styles.img, styles.imgLeft)}
                      />
                      <span className={styles.score}>{group[0].score}</span>
                    </>
                  )}
                  {item.status == 0 || item.status == 3 ? <span className={styles.status}>未开始</span> : null}
                  {item.status == 2 ? <span className={styles.status}>已结束</span> : null}
                  {item.status == 1 ? (
                    <span className={styles.status} style={{ color: 'var(--theme-color)' }}>
                      直播中
                    </span>
                  ) : null}
                  {group.length < 2 ? null : (
                    <>
                      <span className={styles.score}>{group[1].score}</span>
                      <img
                        loading="lazy"
                        src={group[1].image}
                        alt={group[1].name}
                        className={cm(styles.img, styles.imgRight)}
                      />
                      <span className={styles.name}>{group[1].name}</span>
                    </>
                  )}
                </div>
              </Link>
            )
          })}
        </div>
      </div>
    </>
  )
}

export async function getServerSideProps() {
  const resArr = (await Promise.allSettled([getProject({}), getHotRace(), getHeader()]))?.map(item => {
    if (item.value.code) {
      return {}
    }
    return item.value?.data || {}
  })
  const { projectList = [] } = resArr[0]
  const { hotMatchList = [] } = resArr[1]
  let props = {
    layoutProps: {
      noSomeMetaInfo: false,
      url: '/sports',
      title: '体育直播在线，全球高清赛事免费看 - 星视界',
      desc: '星视界体育频道提供高清体育直播及回看，包含海外足球直播赛事、国内外篮球赛事、拳击、排球等及其他综合赛事直播，更有体育直播App提供更多热门体育电视台进一步提升观赛体验。'
    },
    project: projectList || [],
    hotRace: hotMatchList ||[],
    headerInfo: resArr[2]
  }
  return {
    props
  }
}
